package lz77;

import java.util.ArrayList;
import java.util.List;

public class LZ77 {

	public List<LZ77Tupel> compress(String input) {

		List<LZ77Tupel> list = new ArrayList<LZ77Tupel>();
		String dict = "";
		String search;

		int index;
		int matchindex = 0;
		String currentSign = "";
		do {
			search = "";
			do {
				currentSign = getNextSign(input);
				input = trimString(input);
				search += currentSign;
				index = dict.indexOf(search);
				if (index > -1)
					matchindex = index;
			} while (index > -1 && input.length() > 0);

			switch (search.length()) {
			case 1:
				dict += search;
				list.add(new LZ77Tupel(currentSign.charAt(0)));
				break;
			case 2:
				input = currentSign + input;
				dict += search.substring(0, 1);
				list.add(new LZ77Tupel(search.charAt(0)));
				break;
			default:
				dict += search;
				list.add(new LZ77Tupel(matchindex, search.length() - 1,
						currentSign.charAt(0)));
			}
		} while (input.length() > 0);

		return list;
	}

	/*
	 * Get the next sign of the text and remove it from the text
	 */
	private String getNextSign(String text) {
		String s = text.substring(0, 1);
		return s;
	}

	/*
	 * Cuts off the first character of the text
	 */
	private String trimString(String text) {
		return text.substring(1);
	}

	public String decompress(List<LZ77Tupel> list) {
		String out = "";

		for (LZ77Tupel t : list) {
			if (t.getIndex() == 0 && t.getLength() == 0)
				out += t.getChar();
			else
				out += out
						.substring(t.getIndex(), t.getIndex() + t.getLength())
						+ t.getChar();
		}
		return out;
	}
}
